﻿using System;
using System.Collections.Concurrent;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Net;
using System.Net.Http;
using System.Text;
using System.Web.Http;

using ERPStore.Tasks.Extensions;

namespace ERPStore.Tasks.Controllers
{
	public class PushTasksController : ApiController
	{
		private static ERPStore.Services.PushSubscriberService PushSubscriberService
			= new ERPStore.Services.PushSubscriberService();

		public PushTasksController(ERPStore.Logging.ILogger logger)
		{
			this.Logger = logger;
		}

		protected ERPStore.Logging.ILogger Logger { get; private set; }

		public HttpResponseMessage GetUpdates(HttpRequestMessage request)
		{
			request.Authenticate();

			var clientNameHeader = request.Headers.FirstOrDefault(h => "ClientName".Equals(h.Key, StringComparison.InvariantCultureIgnoreCase));
			var clientName = string.Empty;
			if (clientNameHeader.Value != null)
			{
				clientName = clientNameHeader.Value.First();
			}

			var response = request.CreateResponse();
			response.Content = new PushStreamContent((stream, content, context) =>
			{
				var subscriber = new ERPStore.Models.PushSubscriber()
				{
					ClientName = clientName,
					StreamWriter = new StreamWriter(stream)
				};

				PushSubscriberService.Add(subscriber);
			}, "text/plain");
			return response;
		}

		public static void WriteMessage(string message)
		{
			message = "{Message:\"" + message + "\"}";
			PushSubscriberService.WriteMessage(message);
		}

		protected override void Dispose(bool disposing)
		{
			base.Dispose(disposing);
			PushSubscriberService.Dispose();
		}

	}
}
